package day9;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author oldliu
 * @since 1.0
 */
public class TalkServer {
    public static void main(String[] args) {
        try {
            ServerSocket st = new ServerSocket(8888);
            System.out.println("服务器启动，监听在8888端口");
            while (true) {
                Socket s = st.accept();
                System.out.println("ip:" + s.getInetAddress());
                System.out.println("远程端口：" + s.getPort());
                System.out.println(s.getLocalPort() + "本地");
                System.out.println("socket连接建立了。。。" + s);
                InputStream in = s.getInputStream();
                OutputStream out = s.getOutputStream();
                //客户端回，服务器答，
                //BufferedWriter pw=new BufferedWriter(out,true);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                PrintWriter pw = new PrintWriter(out, true);

                try {
                    while (true) {
                        String str = br.readLine();
                        System.out.println("客户端问：" + str);
                        pw.println("你问的:" + str + ",朕知道了");
                        if (str == null || "null".equals(str) || "byebye".equals(str))
                            break;

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println(s + "异常退出了。。。");
                } finally {
                    try {
                        if (s != null && s.isClosed() == false)
                            s.close();
                    } catch (IOException e) {

                    }
                }


            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
